package com.fingard.dsp.bank.directbank.czb02;

import com.fingard.FGBiz;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.*;

public class CZB02Statement extends CZB02Base implements IStatement {
    @Override
    public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();

        // 单笔实时代扣对账单
        String[] realtimeRecRespHeader = getRealTimeStatement(p_reqQrySttm, retAts);
        String realtimeRecTotalNum = getTotalNum(retAts.totalNum);
        if ("-1".equals(realtimeRecRespHeader[0])) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(StringHelper.joinNotEmpty("\r\n", "单笔实时对账单获取失败，原因:" + realtimeRecRespHeader[1]));
        } else {
            if (retAts.getWrittenRdCount() == 0) {
                retAts.writeRespCode("0");
                String respInfo = realtimeRecRespHeader[1];
                if (StringHelper.isNullOrEmpty(respInfo)) {
                    respInfo = "交易为空";
                }
                retAts.writeRespInfo(respInfo);
            } else {
                // 获取成功时写入总笔数
                retAts.isWritedTotalNum(String.valueOf(Integer.parseInt(realtimeRecTotalNum)));
            }
        }
        retAts.writeEnd();
        return retAts;
    }

    private String[] getRealTimeStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
        String[] tmpRespHeader = new String[]{"",""};

        String tmpRespCode = "";
        String tmpRespInfo = "";
        boolean isFinished = false;
        retAts.totalNum = "0";
        int totalNum = 0;

        try{
            ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "");
            if (actItem != null) {
                CZB02Header bankHeader = new CZB02Header();
                bankHeader.transCode = "0007";
                bankHeader.reqSeqNo = p_reqQrySttm.actNum;

                XmlTextWriter xmlWriter = new XmlTextWriter();
                StringBuilder reqMsg = new StringBuilder();

                writeCommonHeader(xmlWriter, actItem, bankHeader);
                xmlWriter.writeStartElement("body");
                xmlWriter.writeElementString("rq", p_reqQrySttm.busDate);//日期
                reqMsg.append("<rq>" + p_reqQrySttm.busDate + "</rq>");//日期
                xmlWriter.writeEndDocument();

                String signMsg = signData(reqMsg.toString(), actItem);
                WriteBankLogLn2("签名原始数据:\r\n" + reqMsg.toString());

                String reqData = xmlWriter.toXmlString().replaceAll("<bz1 />", "<bz1>" + signMsg + "</bz1>");

                String[] tmpStrRet = sendToBank(reqData);
//                String[] tmpStrRet = {"", "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
//                        "<response><head><fhm>000000</fhm><fhxx>交易成功</fhxx><xtlsh>83120191011146230264</xtlsh><jym>0007</jym><khh></khh><jyrq>20191011</jyrq><jysj>191011</jysj></head><body><wjm>20191010_0074_0074_dsdz.txt</wjm></body></response>"};

                if (tmpStrRet[0].length() == 0) {
                    WriteBankLogLn2("浙商单笔实时收付对账单响应数据:\r\n" + tmpStrRet[1]);
                    if (tmpStrRet[1].length() == 0) {
                        tmpRespCode = "-1";
                        tmpRespInfo = "浙商实时收款对账单返回内容为空,请联系浙商相关技术人员!";
                    } else {

                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

                        if (tmpBkReader != null) {
                            tmpRespInfo = tmpBkReader.getFirstText("/response/head/fhxx");
                            tmpRespCode = tmpBkReader.getFirstText("/response/head/fhm");
                            if ("000000".equals(tmpRespCode)) {
                                tmpRespCode = "0";
                                if (tmpBkReader.read("/response/body")) {
                                    tmpRespInfo = tmpBkReader.readedXElement.getSingleText("wjm");
                                }
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpBkReader.getFirstText("/response/head/fhxx");
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                        }
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                }

                tmpRespHeader[0] = tmpRespCode;
                tmpRespHeader[1] = tmpRespInfo;

                if(isFinished || "-1".equals(tmpRespCode)){
                    return tmpRespHeader;
                }

                String tmpFileName = FGBiz.DSPHOME_Parent + File.separator + "statement";
                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                xmlTextWriter.writeStartElement("request");
                xmlTextWriter.writeStartElement("head");
                String username = getBankConfig().getValueAsString("username");
                if (StringHelper.hasAnyChar(username)) {
                    xmlTextWriter.writeElementString("username", username);
                } else {
                    tmpRespHeader[0] = "-1";
                    tmpRespHeader[1] = "请求报文中username节点为空，请检查CZB02/config.xml中'username'节点配置";
                    return tmpRespHeader;
                }
                String password = getBankConfig().getValueAsString("password");
                if (StringHelper.hasAnyChar(password)) {
                    xmlTextWriter.writeElementString("password", password);
                } else {
                    tmpRespHeader[0] = "-1";
                    tmpRespHeader[1] = "请求报文中password节点为空，请检查CZB02/config.xml中'password'节点配置";
                    return tmpRespHeader;
                }
                String opType = getBankConfig().getValueAsString("opType");
                if (StringHelper.hasAnyChar(password)) {
                    xmlTextWriter.writeElementString("optype", opType);//操作类型
                } else {
                    tmpRespHeader[0] = "-1";
                    tmpRespHeader[1] = "请求报文中opType节点为空，请检查CZB02/config.xml中'opType'节点配置";
                    return tmpRespHeader;
                }
                xmlTextWriter.writeEndElement();
                xmlTextWriter.writeStartElement("body");
                String localpath = tmpFileName + File.separator + p_reqQrySttm.busDate + ".txt";
                xmlTextWriter.writeElementString("localpath", localpath);
                xmlTextWriter.writeElementString("remotepath", getBankConfig().getValueAsString("remotepath"));
                xmlTextWriter.writeElementString("filename", tmpRespInfo);
                xmlTextWriter.writeEndDocument();

                tmpStrRet = sendToBanks(xmlTextWriter.toXmlString());
//                tmpStrRet = new String[]{"", "<?xml version=\"1.0\" encoding=\"GBK\"?><response>\n" +
//                        "  <head>\n" +
//                        "    <optype>DOWNLOAD</optype>\n" +
//                        "    <result>000000</result>\n" +
//                        "    <msg>成功</msg>\n" +
//                        "  </head>\n" +
//                        "  <body>\n" +
//                        "    <filesize>134</filesize>\n" +
//                        "  </body>\n" +
//                        "</response>2|0.02|\n" +
//                        "20191010|150100|00000000000001144442|6223093310072150538|0.01|\n" +
//                        "20191010|161813|00000000000001144443|6223093310072150538|0.01|\n"};

                if (tmpStrRet[0].length() == 0) {
                    WriteBankLogLn2("浙商实时收付对账单响应数据:\r\n" + tmpStrRet[1]);
                    if (tmpStrRet[1].length() == 0) {
                        tmpRespCode = "-1";
                        tmpRespInfo = "浙商实时收款对账单返回内容为空,请联系浙商相关技术人员!";
                    } else {
                        String tmpRespXml = tmpStrRet[1].substring(tmpStrRet[1].indexOf("<"), tmpStrRet[1].indexOf("</response>") + 11);
                        String fileContent = tmpStrRet[1].substring(tmpStrRet[1].indexOf("</response>") + 11);

                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRespXml, tmpSbMsg);
                        if (tmpBkReader != null) {
                            String fileSize = tmpBkReader.getFirstText("/response/body/filesize");
                            if (!"".equals(fileSize)) {
                                tmpRespCode = "0";

                                String tmpRetStr = fileContent;
                                String tmpRetStr1 = "";
                                if (tmpRetStr.contains("|")) {
                                    int index = tmpRetStr.indexOf("|");
                                    tmpRetStr1 = tmpRetStr.substring(index-1);

                                    String path = FGBiz.DSPHOME_Parent + File.separator + "statement";
                                    File dir1 = new File(path);
                                    if(!dir1.exists()){
                                        dir1.mkdir();
                                    }
                                    File tmpFile1 = new File(path + File.separator + tmpRespInfo + ".txt");
                                    if(!tmpFile1.exists()){
                                        tmpFile1.createNewFile();
                                        PrintStream ps = null;
                                        try {
                                            ps = new PrintStream(new FileOutputStream(tmpFile1));
                                            ps.println(tmpRetStr1);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        } finally {
                                            if (ps != null) {
                                                ps.close();
                                            }
                                        }
                                    }
                                    WriteBankLogLn2("文件内容:\r\n" + tmpRetStr1);

                                }
                                // 解析返回ATS
                                if (StringHelper.hasAnyChar(tmpRetStr1)) {
                                    tmpRespCode = "0";

                                    StringReader strreader = new StringReader(tmpRetStr1);
                                    BufferedReader tmpreader = new BufferedReader(strreader);
                                    tmpreader.readLine();

                                    while(true) {
                                        String eachline = tmpreader.readLine();
                                        if(eachline == null){
                                            break;
                                        }

                                        String[] eachNodes = eachline.split("\\|");
                                        RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();

                                        if (eachNodes.length == 5) {
                                            totalNum++;
                                            tmpRetDetail.askNumber = eachNodes[2].trim();
                                            tmpRetDetail.oppAct = eachNodes[3].trim();
                                            tmpRetDetail.amount = eachNodes[4].trim();
                                            tmpRetDetail.busTime = eachNodes[0]+eachNodes[1];
                                            tmpRetDetail.transState = TransState.Success;
                                            tmpRetDetail.cdFlag = "22";

                                            retAts.writeRetDetail(tmpRetDetail);
                                        } else {
                                            tmpRespCode = "-1";
                                            tmpRespInfo = "浙商对账单返回明细列数非法";
                                        }
                                    }
                                }
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpBkReader.getFirstText("/response/head/fhxx");
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpSbMsg.toString();
                        }
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpStrRet[1];
                }
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = "未找到账号:[" + p_reqQrySttm.actNum + "]商户配置信息!";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.totalNum = String.valueOf(totalNum);
        tmpRespHeader[0] = tmpRespCode;
        tmpRespHeader[1] = tmpRespInfo;
        return tmpRespHeader;
    }
}
